import LoginForHeader from "./LoginForHeader";
import LoginForFooter from "./LoginForFooter";
import useForm from "@module/useForm";
import Base64 from "@module/Base64";
import UrlHooks from "../../pages/ruijing/common/utils/urlHook.js";
import HttpUtils from "../../pages/ruijing/common/utils/HttpUtils";
import "@module/rsa/jsencrypt.min.js";
import ZenUI from "@module/../components/ZenUI/ZenUI";

import img0 from "../images/login_banner.png";
import "../../pages/ruijing/index/zen_init.css";
import "./Login.css";

export default function LoginPage(props) {
    const params = $state.params;
    const { loginSite, registerType, suppName, token } = params || {};
    const [currentConfig, updateCurrentConfig] = usePartState({});
    let thirdLoginSite = ["hms", "whse"];

    //生命周期 页面渲染完后再执行，每次刷新前也执行
    const { isModalLogin, hideTabIndex, rediretTo } = props;
    React.useEffect(() => {
        if (Uts.contain(thirdLoginSite, params.loginSite)) {
            StateApi.updateStoreState("commonFooterConfig", { hideFooter: 1 });
        }
        return function() {
            StateApi.updateStoreState("commonFooterConfig", {});
        };
    });

    React.useEffect(() => {
        isAutoLogin(); //先判断是否是自动登录
        getPublicKey();
    }, []);

    function validateEncrypt(params) {
        let validateEncryptEP = "/auth/rsa/decrypt";
        let headerConfig = {
            contentType: 1,
            Authorization: "basic " + new Base64().encode("webapp:webapp")
        };
        REST.post(validateEncryptEP, params, "noInfo", headerConfig).then(
            function(data) {
                console.log(data);
                // updateCurrentConfig({ publickey: data });
            },
            function(error) {
                console.log(error);
            }
        );
    }

    function getPublicKey() {
        let getPublicKeyEP = "/auth/rsa/publickey";
        REST.post(getPublicKeyEP, {}).then(
            function(data) {
                //console.log(data);
                updateCurrentConfig({ publickey: data });
            },
            function(error) {
                //console.log(error);
            }
        );
    }

    function isAutoLogin() {
        let autoLoginInfo = Uts.storage.get("autoLoginInfo");
        if (autoLoginInfo && autoLoginInfo.autoLogin) {
            doLogin(autoLoginInfo);
        }
    }

    //定义表单 useForm（回调，默认值，表单名）
    const { formData, handleChange, handleSubmit } = useForm(
        doSubmit,
        {},
        "loginForm"
    );

    //定义全局变量 const [scope值，更新方法] = React.useState({初始化的值});
    let actTabIndex = 1;
    if (hideTabIndex == 1) {
        //隐藏掉采购人登录
        actTabIndex = 2;
    }
    const [currentScope, updateCurrentScope] = React.useState({
        actTabIndex: actTabIndex
    });

    //更新视图数据 私有的方法前缀用_
    function _updateData(value) {
        let newValue = { ...currentScope, ...value };
        // console.log(newValue);
        updateCurrentScope(newValue);
    }

    // function getIdentity() {
    //     let url=`/store/api/username`
    //     let params={}
    //
    //     REST.get(url)
    //         .then(res=>{
    //             console.log(res)
    //             // return
    //             location.href=`#/`
    //         },(err)=>{
    //
    //         })
    // }

    //获取供应商权限
    function getIdentity() {
        let url = `/suppliers/identity`;
        let params = {};
        REST.get(url).then(
            res => {
                console.log(res);
                // Uts.setCookie("suppAuths", res.authorities);
                Uts.setCookieMt({
                    suppAuths: res.authorities,
                    access_token: global.$access_token,
                    id1: res.id,
                    suppId: res.suppId,
                    username1: res.supp.fsuppname || res.supp.femail,
                    userEmail1: res.supp.femail,
                    userReal: res.username,
                    frozenOrgIds: res.frozenOrgIds
                });
                if (res.supp.fmobile != null && res.supp.fmobile != "") {
                    Uts.setCookie("svm", res.supp.fmobile);
                }

                Uts.storage.set("supp_orgs", res.orgModels);

                /*$.cookie('id1', datas.id, cookieDomain);
                $.cookie('username1', datas.supp.fsuppname || datas.supp.femail, cookieDomain);
                $.cookie('userEmail1', datas.supp.femail, cookieDomain);
                $.cookie('userReal', datas.username, cookieDomain);
                $.cookie('suppId', datas.suppId, cookieDomain);
                $.cookie('frozenOrgIds', datas.frozenOrgIds, cookieDomain);
                $.cookie('suppAuths',JSON.stringify(datas.authorities),cookieDomain);
                $.cookie('loginToken', datas.loginToken, cookieDomain);
                if(datas.supp.fmobile != null && datas.supp.fmobile != '') {
                    $.cookie("svm", datas.supp.fmobile, cookieDomain);
                    smh = datas.supp.fmobile.length;
                }*/
                // Uts.storage.set("suppAuths", res.authorities);
                // window.location.href=`../purchaser/index.html#helpdetails/d6367ca4-151d-493e-8368-5fd6760e4f2c/2019-05-06`;
                if (rediretTo) {
                    // location.href=rediretTo
                    // alert('xxx')
                    console.log(rediretTo);
                    // location.href=rediretTo
                    location.reload();

                    return;
                }
                location.href = UrlHooks["supplierhp"];
            },
            err => {}
        );
    }

    //refreshToken的作用，一、用来刷新acess_token, 二、用来做自动登陆
    function setRefreshToken(data) {
        let refreshToken = Uts.storage.get("refreshToken");
        //首次登录没有refreshToken的时候，每次登录refresh_token都不同，取最新的
        if (!refreshToken || data.refresh_token != refreshToken) {
            Uts.storage.set("refreshToken", data.refresh_token);
        }
    }

    function setAutoLoginToLocalStorage(autoLogin, registerType) {
        let autoLoginInfo = {
            autoLogin: autoLogin,
            registerType: registerType
        };
        Uts.storage.set("autoLoginInfo", autoLoginInfo);
    }

    //提交事件
    function doSubmit() {
        console.log(formData);
        if (!formData.username) {
            ZenUI.ST("用户名不能为空！");
            return false;
        }
        if (!formData.password) {
            ZenUI.ST("密码不能为空！");
            return false;
        }
        doLogin();
    }

    function doLogin(hasAutoLoginInfo) {
        ZenUI.SL(60);
        let loginUrl = "/auth/oauth/token";
        let loginData = {
            grant_type: "password", //授权类型 password/refresh_token
            username: formData.username,
            password: formData.password
            // type: currentScope.actTabIndex, //用户类型,1-采购商 2-供应商 3-平台管理 4-供应商多账户
            // realm: Uts.getEnv().env != "localhost" ? Uts.getEnv().env : "uat" //环境
        };

        if (currentScope.actTabIndex == 1) {
            loginData.type = 1;
        } else {
            loginData.type = 4;
        }

        if (hasAutoLoginInfo && hasAutoLoginInfo.autoLogin) {
            const refreshToken = Uts.storage.get("refreshToken");
            loginData = {
                grant_type: "refresh_token", //授权类型 password/refresh_token
                refresh_token: refreshToken,
                // type: currentScope.actTabIndex, //用户类型,1-采购商 2-供应商 3-平台管理 4-供应商多账户
                realm: "uat" //环境
            };
            if (hasAutoLoginInfo.registerType == 1) {
                loginData.type = 1;
            } else {
                loginData.type = 4;
            }
        } else {
            if (!currentConfig.publickey) {
                ZenUI.ST("获取加密公钥失败，请刷新重试");
                ZenUI.HL(60);
                return false;
            }
            let encryptConfig = new JSEncrypt();
            encryptConfig.setPublicKey(currentConfig.publickey);
            // console.log(loginData);
            loginData = { data: encryptConfig.encrypt(Uts.toStr(loginData)) };
        }

        let headerConfig = {
            contentType: 1,
            Authorization: "basic " + new Base64().encode("webapp:webapp")
        };
        Uts.setCookie("accrosToken", "");
        Uts.setCookie("SPAccrosToken", "");
        Uts.setCookie("orgId", "");
        console.log(loginData);

        // return validateEncrypt({ encrypt: loginData });
        REST.post(loginUrl, loginData, "dis", headerConfig).then(
            function(data) {
                ZenUI.HL();
                console.log(data);
                if (data.access_token) {
                    global.hasLogin = true;
                    console.log("登录成功");
                    // let _data=Object.assign(data,{createTime:new Date().getTime()})
                    Uts.storage.set("loginTokenInfo", data); //保留登录信息缓存
                    setRefreshToken(data); //保存或更新refresh_token
                    setAutoLoginToLocalStorage(
                        currentScope.autoLogin,
                        currentScope.actTabIndex
                    ); //保存是否是自动登录,是采购人还是供应商
                    //1：采购，2：供应商
                    if (hasAutoLoginInfo && hasAutoLoginInfo.autoLogin) {
                        if (hasAutoLoginInfo.registerType == 1) {
                            Uts.setCookie("accrosToken", data.access_token);
                            global.$access_token = data.access_token;
                            // getIdentity();

                            if (Uts.contain(thirdLoginSite, params.loginSite)) {
                                Uts.routeToDomain(params.loginSite, "control");
                            } else {
                                if (rediretTo) {
                                    location.reload();
                                    return;
                                }
                                location.href = `#/`;
                            }
                        } else if (hasAutoLoginInfo.registerType == 2) {
                            Uts.setCookie("SPAccrosToken", data.access_token);
                            global.$access_token = data.access_token;
                            getIdentity();
                            // location.href = UrlHooks["supplierhp"];
                        }
                    } else {
                        if (currentScope.actTabIndex == 1) {
                            Uts.setCookie("accrosToken", data.access_token);
                            global.$access_token = data.access_token;
                            // getIdentity();

                            if (Uts.contain(thirdLoginSite, params.loginSite)) {
                                Uts.routeToDomain(params.loginSite, "control");
                            } else {
                                if (rediretTo) {
                                    location.reload();
                                    return;
                                }
                                location.href = `#/`;
                            }
                        } else if (currentScope.actTabIndex == 2) {
                            Uts.setCookie("SPAccrosToken", data.access_token);
                            global.$access_token = data.access_token;
                            getIdentity();
                            // location.href = UrlHooks["supplierhp"];
                        }
                    }
                }
            },
            function(error) {
                ZenUI.HL();
                console.log(error);
                console.log(error.response.data);
                _updateData({ errorInfo: error.response.data.message });
            }
        );
    }

    function goToFindPassword() {
        $state.go({
            stateName: "/forgetpwd",
            params: {
                step: 1,
                registerType: currentScope.actTabIndex,
                forgetPwd: 1
            }
        });
    }

    function goToRegister(argument) {
        $state.go({
            stateName: "/register",
            params: {
                step: 1,
                registerType: currentScope.actTabIndex //注册类型：1采购人注册，2供应商注册，3找回密码
            }
        });
    }

    function closeLoginModal() {
        if (isModalLogin) {
            alert("close ");
        }
    }

    return (
        <div>
            <LoginForHeader loginSite={params.loginSite} hide={isModalLogin} />

            <div
                className={Uts.sc([
                    isModalLogin ? "" : "login-wrap",
                    Uts.contain(thirdLoginSite, params.loginSite)
                        ? "hms_login-wrap"
                        : ""
                ])}
            >
                <div
                    className={
                        isModalLogin
                            ? "login-content-wrap-modal"
                            : "content-wrap zen_ps-re zen_z-i-1"
                    }
                >
                    {!Uts.contain(thirdLoginSite, params.loginSite) &&
                        !isModalLogin && (
                            <img
                                className="zen_ps-ab zen_t-60 zen_z-i-2"
                                src={img0}
                            />
                        )}
                    <form
                        onClick={e => {
                            e.stopPropagation();
                        }}
                        name="loginForm"
                        onSubmit={handleSubmit}
                        className={
                            isModalLogin
                                ? "login-new-form-modal"
                                : Uts.sc([
                                      "login-new-form",
                                      Uts.contain(
                                          thirdLoginSite,
                                          params.loginSite
                                      )
                                          ? "hms_login-new-form"
                                          : ""
                                  ])
                        }
                    >
                        {Uts.contain(thirdLoginSite, params.loginSite) && (
                            <div className=" zen_fs-16 zen_w-p100 zen_t-c">
                                <span className="zen_il-bl zen_fs-18">
                                    账号登录
                                </span>
                            </div>
                        )}
                        {!Uts.contain(thirdLoginSite, params.loginSite) && (
                            <div className=" zen_fs-16 zen_cs-pt a_color-gray6 zen_flex zen_w-300">
                                {hideTabIndex == 1 ? null : (
                                    <span
                                        id="a_purchase"
                                        className={Uts.sc([
                                            currentScope.actTabIndex == 1
                                                ? "a_active"
                                                : "",
                                            "zen_il-bl zen_w-90 zen_p-v-5 zen_m-r-35 zen_m-l-10 a_tab-bd zen_t-c"
                                        ])}
                                        onClick={e => {
                                            formData.username = "";
                                            formData.password = "";
                                            _updateData({
                                                actTabIndex: 1,
                                                errorInfo: ""
                                            });
                                        }}
                                    >
                                        采购人登录
                                    </span>
                                )}
                                {hideTabIndex == 2 ? null : (
                                    <span
                                        id="a_supplier"
                                        className={Uts.sc([
                                            currentScope.actTabIndex == 2
                                                ? "a_active"
                                                : "",
                                            "zen_il-bl zen_w-90 zen_p-v-5 zen_m-l-35 zen_m-r-10 a_tab-bd zen_t-c"
                                        ])}
                                        onClick={e => {
                                            formData.username = "";
                                            formData.password = "";
                                            _updateData({
                                                actTabIndex: 2,
                                                errorInfo: ""
                                            });
                                        }}
                                    >
                                        供应商登录
                                    </span>
                                )}
                            </div>
                        )}
                        <div className="login-info zen_fs-14">
                            <div
                                className={Uts.sc([
                                    currentScope.userIpt ? "a_iptOnFocus" : "",
                                    "login-item zen_ps-re zen_m-b-20"
                                ])}
                            >
                                <span className="zen_ps-ab zen_b-10 zen_l-0 zen_w-16 zen_h-18 a_userIcon" />
                                <input
                                    className="zen_w-245 zen_h-30 zen_p-l-5 login-new-input"
                                    type="text"
                                    name="username"
                                    placeholder="邮箱 / 用户名"
                                    onFocus={e => {
                                        _updateData({ userIpt: true });
                                    }}
                                    onBlur={e => {
                                        _updateData({ userIpt: false });
                                    }}
                                    onInput={handleChange}
                                    value={formData.username}
                                    required
                                />
                                {formData.username && (
                                    <span
                                        className="zen_ps-ab zen_t-13 zen_r-5 zen_w-16 zen_h-16 a_delIcon"
                                        onClick={e => {
                                            formData.username = "";
                                            _updateData({ userIpt: false });
                                        }}
                                    />
                                )}
                            </div>
                            <div
                                className={Uts.sc([
                                    currentScope.passwordIpt
                                        ? "a_iptOnFocus"
                                        : "",
                                    "login-item zen_ps-re zen_m-b-20"
                                ])}
                            >
                                <span className="zen_ps-ab zen_b-10 zen_l-0 zen_w-16 zen_h-20 a_passwordIcon" />
                                <input
                                    className="zen_w-245 zen_h-30 zen_p-l-5 login-new-input"
                                    type="password"
                                    name="password"
                                    placeholder="密码"
                                    onFocus={e => {
                                        _updateData({ passwordIpt: true });
                                    }}
                                    onBlur={e => {
                                        _updateData({ passwordIpt: false });
                                    }}
                                    onInput={handleChange}
                                    value={formData.password}
                                    required
                                />

                                {formData.password && (
                                    <span
                                        className="zen_ps-ab zen_t-13 zen_r-5 zen_w-16 zen_h-16 a_delIcon"
                                        onClick={e => {
                                            formData.password = "";
                                            _updateData({ passwordIpt: false });
                                        }}
                                    />
                                )}
                            </div>
                            {currentScope.errorInfo && (
                                <div className="zen_red">
                                    {currentScope.errorInfo}
                                </div>
                            )}
                            <div
                                className={Uts.sc([
                                    "zen_clf zen_w-270 zen_h-24 zen_l-h-24",
                                    currentScope.errorInfo
                                        ? "zen_m-v-10"
                                        : "zen_m-v-30"
                                ])}
                            >
                                <div
                                    className={Uts.sc([
                                        currentScope.autoLogin
                                            ? "a_iptOnFocus"
                                            : "",
                                        "zen_f-left a_clolr-link zen_cs-pt"
                                    ])}
                                    onClick={e => {
                                        let autoLogin = !currentScope.autoLogin;
                                        _updateData({
                                            autoLogin: autoLogin
                                        });
                                    }}
                                >
                                    <span className="zen_il-bl zen_w-16 zen_h-16 a_checkIcon zen_v-m zen_m-r-5" />
                                    自动登录
                                </div>
                                <a
                                    className="zen_f-right a_clolr-link zen_cur-p"
                                    // href={UrlHooks["findpassword"]}
                                    onClick={goToFindPassword}
                                >
                                    忘记密码 ?
                                </a>
                            </div>
                            <div className="zen_m-b-8">
                                <button
                                    type="submit"
                                    className={Uts.sc([
                                        "a_submit-btn",
                                        Uts.contain(
                                            thirdLoginSite,
                                            params.loginSite
                                        )
                                            ? "hms_bg-green"
                                            : ""
                                    ])}
                                >
                                    登录
                                </button>
                            </div>
                            {currentScope.actTabIndex == 2 && (
                                <div className={"zen_clf"}>
                                    <a
                                        className="a_clolr-link zen_f-right zen_cur-p"
                                        // href={UrlHooks["providerfirst"]}
                                        onClick={goToRegister}
                                    >
                                        注册
                                    </a>
                                </div>
                            )}
                        </div>
                    </form>
                </div>
            </div>

            {/*<LoginForFooter />*/}
        </div>
    );
}
